package com.xinwei.shard.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinwei.shard.entity.User;
import com.xinwei.shard.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("add")
    public boolean createUser(@RequestBody User user) {
        return userService.save(user);
    }

    @PostMapping("update")
    public boolean updateByAge(@RequestBody User user) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        // 分片数据不允许更新,否则会报错
        updateWrapper.eq(User::getAge, user.getAge()).set(User::getName, user.getName());
        return userService.update(updateWrapper);
    }

    @GetMapping("delete")
    public boolean deleteUserByAge(@RequestParam("age") Integer age) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAge, age);
        return userService.remove(queryWrapper);
    }

    @GetMapping("/{age}")
    public List<User> getUserByAge(@PathVariable Integer age) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAge, age);
        return userService.list(queryWrapper);
    }

    @GetMapping("/page")
    public IPage<User> getUserByPage(@RequestParam("pageNum") Integer pageNum) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        IPage<User> iPage = new Page<>(pageNum, 10);
        return userService.page(iPage);
    }

}

